package com.xzcs.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author chang
 * @date 2016-11-24 13:42
 */
public class MyExceptionHandler implements HandlerExceptionResolver {

    public Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest,
                                         HttpServletResponse httpServletResponse,
                                         Object handler, Exception e) {
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("errorCode", httpServletRequest.getAttribute("javax.servlet.error.status_code"));
        model.put("errorMessage", httpServletRequest.getAttribute("javax.servlet.error.message"));
        model.put("errorType", httpServletRequest.getAttribute("javax.servlet.error.exception_type"));

        //logger.error("系统异常", e);

        HttpStatus httpStatus = getStatus(httpServletRequest);
        if (httpStatus.value() == 400) {
            return new ModelAndView("html/error/400", model);
        } else if (httpStatus.value() == 403) {
            return new ModelAndView("html/error/403", model);
        } else if (httpStatus.value() == 500) {
            return new ModelAndView("html/error/500", model);
        }
        return new ModelAndView("html/error/500", model);
    }

    protected HttpStatus getStatus(javax.servlet.http.HttpServletRequest request) {
        Integer statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code");
        if(statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        } else {
            try {
                return HttpStatus.valueOf(statusCode.intValue());
            } catch (Exception var4) {
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }
        }
    }
}
